package com.atguigu.spzx.manger.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manger.mapper.SysUserMapper;
import com.atguigu.spzx.manger.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        //1 获取用户名

        String input_username = loginDto.getUserName();
        //2 查询表 sys_user

        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(input_username);

        //校验验证码
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        //从redis中取出数据 做判断
        String validateKey = redisTemplate.opsForValue().get("user:validation" + codeKey);
        if (StrUtil.isEmpty(validateKey) || !StrUtil.equalsAnyIgnoreCase(captcha, validateKey)) {
            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        // 删除redis中的这条数据
        redisTemplate.delete("user:validation" + codeKey);


        //3 查不到 抛异常
        if(null == sysUser){
            throw new GuiguException(501,"账号不存在！");
        }
        //4 查询成功
        //5 比较密码 密码加密
        String password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        //6 密码是否一致
        if(!password.equals(input_password)){
            throw new GuiguException(502,"密码错误！");
        }

        //7 登入成功 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //8 把当前用户信息放到redis
        redisTemplate.opsForValue().set("user:login"+token, JSON.toJSONString(sysUser),7, TimeUnit.DAYS);

        //9 返回对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    /**
     * 获取验证码
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        // 1 使用hutool工具类生成验证码
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(200, 40, 4, 3);
        String code = circleCaptcha.getCode(); // 作为存放在redis中的key 用户登入后校验
        String imageBase64 = circleCaptcha.getImageBase64();
        // 2 存放到redis中
        String codeKey = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set("user:validation" + codeKey, code,4,TimeUnit.DAYS);
        //同步到ValidateCodeVo实体类中
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);
        // 3 同步数据
        return validateCodeVo;
    }

    /**
     * 获取userInfo
     * @param token
     * @return
     */
    @Override
    public SysUser getUserInfo(String token) {
        String userInfoString = redisTemplate.opsForValue().get("user:login" + token);
        SysUser userInfo = JSON.parseObject(userInfoString, SysUser.class);
        return userInfo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login"+token);
    }


}
